package com.zjt.quartz;

import com.zjt.dao.IBarCodeJobDao;
import com.zjt.dao.brandcategpry.IBrandDao;
import com.zjt.dao.codecenter.ICenterProductDao;
import com.zjt.dao.factory.IFactoryInfoDao;
import com.zjt.dao.product.IProductInfoDao;
import com.zjt.entity.BarCodeJob;
import com.zjt.entity.brandcategory.Brand;
import com.zjt.entity.codecenter.CenterProduct;
import com.zjt.entity.factory.FactoryInfo;
import com.zjt.entity.product.ProductInfo;
import com.zjt.entity.product.QrCode;
import com.zjt.service.IStaticParameterService;
import com.zjt.service.IXmlDocumentService;
import com.zjt.service.product.ICodeService;
import com.zjt.service.product.IProductService;
import com.zjt.utils.DateUtil;
import com.zjt.vo.ProductDataVO;
import com.zjt.web.api.vo.base.PageVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

import java.util.List;
/**
 * Created with IntelliJ IDEA.
 * User: xueyanbeijing
 * Date: 12-9-1
 * Time: PM9:25
 * 定时器工作程序   接口定义与实现
 * To change this template use File | Settings | File Templates.
 */

@Component
public class QuartzJob {
    private static Logger logger = LoggerFactory.getLogger(QuartzJob.class);
    private IBarCodeJobDao barCodeJobDao;
    private IXmlDocumentService xmlDocumentService;
    private IBrandDao brandDao;
    private IProductInfoDao productInfoDao;
    private IFactoryInfoDao factoryInfoDao;
    private ICenterProductDao centerProductDao;

    private ICodeService codeService;
    private IProductService productService;
    private IStaticParameterService staticParameterService;
    private static long initQrNum = 10;

    @Autowired
    public void setProductService(IProductService productService) {
        this.productService = productService;
    }

    @Autowired
    public void setCodeService(ICodeService codeService) {
        this.codeService = codeService;
    }
    @Autowired
    public void setBrandDao(IBrandDao brandDao) {
        this.brandDao = brandDao;
    }
    @Autowired
    public void setProductInfoDao(IProductInfoDao productInfoDao) {
        this.productInfoDao = productInfoDao;
    }
    @Autowired
    public void setFactoryInfoDao(IFactoryInfoDao factoryInfoDao) {
        this.factoryInfoDao = factoryInfoDao;
    }
    @Autowired
    public void setCenterProductDao(ICenterProductDao centerProductDao) {
        this.centerProductDao = centerProductDao;
    }

    @Autowired
    public void setStaticParameterService(IStaticParameterService staticParameterService) {
        this.staticParameterService = staticParameterService;
    }

    @Autowired
    public void setXmlDocumentService(IXmlDocumentService xmlDocumentService) {
        this.xmlDocumentService = xmlDocumentService;
    }

    @Autowired
    public void setBarCodeJobDao(IBarCodeJobDao barCodeJobDao) {
        this.barCodeJobDao = barCodeJobDao;
    }

    /**
     * 自动从表s_bar_code_job表中的status为0,采集
     * 从物码中心采集 的状态为 1　　
     * 将来会有：2，厂端，3，手动录入
     */
    public void  getProductDataFromHttpGet()
    {
       //TODO 如果数据库中无此条形码信息  由启动条形码采集程序，将物码中心数据入库
       //EAN－13通用商品条形码一般由前缀部分、制造厂商代码、商品代码和校验码组成
       //商品条形码中的前缀码是用来标识国家或地区的代码，赋码权在国际物品编码协会,
       //如00-09代表美国、加拿大。45－49代表日本。690-692代表中国大陆，471代表我国台湾地区，489代表香港特区。
       //制造厂商代码的赋权在各个国家或地区的物品编码组织，
       //我国由国家物品编码中心赋予制造厂商代码。
       //商品代码是用来标识商品的代码，赋码权由产品生产企业自己行使，生产企业按照规定条件自己决定在自己的何种商品上使用哪些阿拉伯数字为商品条形码。
       //商品条形码最后用1位校验码来校验商品条形码中左起第l－12数字代码的正确性。
        PageRequest pageRequest = new PageRequest(1,30, Sort.Direction.ASC,"id");
        List<BarCodeJob> barCodeJobList = this.barCodeJobDao.findByCompleteFlagAndStatus(-3,0,pageRequest);
        if (barCodeJobList!=null)
        {
            //逻辑顺序：企业库--》商标库--》临时产品库--》生产库的产品表
            //productDataVO  必须有值。
            String urlPath = staticParameterService.getParameterValueByName("getProductDataByBarCodeUrl");
            String clientID = staticParameterService.getParameterValueByName("clientID");
            for (BarCodeJob barCodeJob:barCodeJobList)
            {
                    boolean hasGet = false;
                    boolean doFlag = false;//当前是否采集到
                    long factoryId_pf = 0;//待插入产品商标关联表中的ID
                    int completeFlag = -3;////-3（两者都没有）,-2（无名称，有企业信息）,-1（无企业，有名称信息），1（名称和企业都有）
                    int codeValueStatus = -1;
                //条码状态 默认为-1
                //0:经查,该商品条码未在中国物品编码中心注册,
                //1:经查,该商品条码已在中国物品编码中心注册
                //2:经查,该商品已在中国物品编码中心注册，但商品信息未按规定通报
                //3:经查,该厂商识别代码已于1999年XX月XX日注销，请关于产品生产日期
                    String url = urlPath +"?clientID="+ clientID+"&barcode="+barCodeJob.getCodeValue().trim();
                    ProductDataVO productDataVO = null;
                   logger.info("start get from http url="+url);
                try
                    {
                        Thread.sleep(5000);//等待5秒
                        productDataVO = this.xmlDocumentService.getProductDataFromHttpGet(url);
                        hasGet = true;//将采集标志置为true 以防止重复
                    }catch (Exception e){
                        logger.info("exception get url xmlDocumentService ="+e);
                        logger.info("exception "+e.getMessage()+"productDataVO="+productDataVO.toString());
                    }
                    ProductInfo productInfo = null;//  当前库中是否有此条码数据；临时用。
                    if (productDataVO!=null)
                    {
                        productInfo = this.productInfoDao.findByCodeValue(barCodeJob.getCodeValue());
                        productDataVO.setBarCode(barCodeJob.getCodeValue());

                        if (productDataVO.getFirmName()!=null&&productDataVO.getFirmName().length()>0)
                        {
                            codeValueStatus = 1;
                            completeFlag = completeFlag + 1;  //-2
                        }
                        else if (productDataVO.getItemName()!=null&&productDataVO.getItemName().length()>0)
                        {
                            completeFlag = completeFlag + 1; //-1
                            codeValueStatus = 2;
                        } else   codeValueStatus = 0;


                        doFlag = true;//已从物码中心采到数据
                    //TODO 入生产库的企业表
                        try
                        {
                            List<FactoryInfo> tempList = null;
                            if (productDataVO.getFirmName()!=null&&productDataVO.getFirmName().length()>0)
                                tempList = this.factoryInfoDao.findByChName(productDataVO.getFirmName().trim());
                            if (tempList!=null&&tempList.size()==0)//不存在
                            {
                                FactoryInfo factoryInfo1 = new FactoryInfo();
                                factoryInfo1.setAddress(productDataVO.getAddress());
                                factoryInfo1.setChName(productDataVO.getFirmName());
                                if (productDataVO.getExtension()!=null&&productDataVO.getExtension().length()>0)
                                    factoryInfo1.setExtension(productDataVO.getExtension());
                                factoryInfo1.setCreateDate(DateUtil.getCurrentDate());
                                factoryInfo1.setUpdateDate(DateUtil.getCurrentDate());
                                factoryInfo1.setEnableFlag("Y");
                                factoryInfo1.setEmail("");
                                factoryInfo1.setContact("");
                                factoryInfo1.setDescription("");
                                factoryInfo1.setHttpweb("");
                                factoryInfo1.setShopDescription("");
                                factoryInfo1.setTel("");
                                //logger.info("待入库的企业表对像 factoryInfo1="+factoryInfo1.toString());
                                factoryInfo1 = this.factoryInfoDao.save(factoryInfo1);
                                if (factoryInfo1!=null) factoryId_pf = factoryInfo1.getId();
                            }else //存在
                                factoryId_pf = tempList.get(0).getId();
                        }catch (Exception e3){
                            logger.error("入生产库的企业表 error"+e3);
                        }
                        //TODO 入品牌库（商标）
                        try
                        {
                            Brand brand = null;
                            //logger.info("待入库的商标 productVO="+productDataVO.toString());
                            if (productDataVO.getBrandName()!=null&&productDataVO.getBrandName().length()>0)
                            {
                                List<Brand> tempList = this.brandDao.findByChName(productDataVO.getBrandName().trim());
                                if (tempList!=null&&tempList.size()>0)
                                    brand = tempList.get(0);
                                tempList = null;
                            }
                            if (brand!=null)
                            {
                                Brand brand1 = new Brand();
                                brand1.setCategoryCount(0);
                                brand1.setAlias(productDataVO.getBrandName());
                                brand1.setChName(productDataVO.getBrandName());
                                brand1.setCreateDate(DateUtil.getCurrentDate());
                                brand1.setUpdateDate(DateUtil.getCurrentDate());
                                brand1.setEnableFlag("Y");
                                brand1.setCategoryCount(brand.getCategoryCount());
                                brand1.setProductCount(brand.getProductCount());
                                brand1.setFactoryId(brand.getFactoryId());
                                brand1.setId(brand.getId());
                                brand1.setStatus(1);
                                brand1 = this.brandDao.save(brand1);
                                productDataVO.setBrandId(brand1.getId());//设置待插入产品表的品牌ID
                                //logger.info("更新商标库成功，企业与品牌，商标关联的信息："+factoryId_pf+":brandId:"+brand.getId());
                            }else//TODO 未找到，重新插入
                            {
                                Brand brand1 = new Brand();
                                brand1.setCategoryCount(0);
                                brand1.setAlias(productDataVO.getBrandName());
                                brand1.setChName(productDataVO.getBrandName());
                                brand1.setCreateDate(DateUtil.getCurrentDate());
                                brand1.setUpdateDate(DateUtil.getCurrentDate());
                                brand1.setEnableFlag("Y");
                                brand1.setCategoryCount(0);
                                brand1.setProductCount(0);
                                //TODO 处理企业与商标的关系数据：
                                brand1.setFactoryId(factoryId_pf);
                                brand1.setStatus(1);
                                brand1 = this.brandDao.save(brand1);
                                productDataVO.setBrandId(brand1.getId());//设置待插入产品表的品牌ID
                                //logger.info("新增商标库成功，企业与品牌，商标关联的信息："+factoryId_pf+":brandId:"+brand.getId());
                            }
                        }catch (Exception e4){
                            logger.error("入品牌库（商标） error"+e4);
                        }

                //TODO 入产品表，临时和生产库
                if (productInfo==null)//不存在，才去采集
                {
                    //TODO 入center库
                    this.insertCenterProductVO(productDataVO);
                    //TODO 入生产库  将来加入审核机制后，待审核状态的，enable_flag  为 A
                    //当前barcode不存在，
                    ProductInfo productInfo1 = null;
                    productInfo1 = this.insertProduct(productDataVO);
                    //logger.info("成功入生产库的产品表：productDataVO="+productInfo1.toString());
                }
           }else//未在中国物码中心注册
           {
                doFlag = false;

           }
           //end if (productDataVO!=null)
         logger.info("end get from http url="+url);
                 //TODO 更改标记    status 0  须读取，1  成功从物码中读到 -1 物码中心无数据   2成功从厂商家读取  -2厂商接口无法读取   3人工成功录入  -3人工录入失败
                int status = 0;
                if (doFlag==true&&hasGet==true)
                   status = 1;
                else if (doFlag==false)//物码中心无数据
                    status = -1;//未采集到
                else status = 0;//物码中心有，但未采集到。

                BarCodeJob barCodeJob1 = new BarCodeJob();
                barCodeJob1.setCodeType(barCodeJob.getCodeType());
                barCodeJob1.setCodeValue(barCodeJob.getCodeValue());
                barCodeJob1.setStatus(status);
                barCodeJob1.setUserId(barCodeJob.getUserId());
                barCodeJob1.setCreateDate(barCodeJob.getCreateDate());
                barCodeJob1.setEnableFlag(barCodeJob.getEnableFlag());
                barCodeJob1.setUpdateDate(DateUtil.getCurrentDate());
                barCodeJob1.setId(barCodeJob.getId());
                barCodeJob1.setCompleteFlag(completeFlag);
                this.barCodeJobDao.save(barCodeJob1);
            }
        }

    }


    /**
     * 入中心库
     * @param productDataVO
     */
    private boolean insertCenterProductVO(ProductDataVO productDataVO)
    {
        boolean doFlag = false;
        //TODO 入center库
        try{
            CenterProduct centerProduct= new CenterProduct();
            centerProduct.setAddress(productDataVO.getAddress());
            centerProduct.setFirmName(productDataVO.getFirmName());
            centerProduct.setExtension(productDataVO.getExtension());
            centerProduct.setCreateDate(DateUtil.getCurrentDate());
            centerProduct.setUpdateDate(DateUtil.getCurrentDate());
            centerProduct.setEnableFlag("Y");
            centerProduct.setDepth(productDataVO.getDepth());
            centerProduct.setBrandName(productDataVO.getBrandName());
            centerProduct.setClassCode(productDataVO.getClassCode());
            centerProduct.setDescription(productDataVO.getDescription());
            centerProduct.setFirmExtension(productDataVO.getFirmExtension());
            centerProduct.setFirmName(productDataVO.getFirmName());
            centerProduct.setGrossWeight(productDataVO.getGrossWeight());
            centerProduct.setGtin(productDataVO.getGtin());
            centerProduct.setHeight(productDataVO.getHeight());
            centerProduct.setItemName(productDataVO.getItemName());
            centerProduct.setNetContent(productDataVO.getNetContent());
            centerProduct.setPackagingMaterialCode(productDataVO.getPackagingMaterialCode());
            centerProduct.setShortDescription(productDataVO.getShortDescription());
            centerProduct.setPackagingTypeCode(productDataVO.getPackagingTypeCode());
            centerProduct.setWidth(productDataVO.getWidth());
            centerProduct.setNetWeight(productDataVO.getNetWeight());
            //logger.info("待入库的正式的产品库 centerProduct="+centerProduct.toString());
            this.centerProductDao.save(centerProduct);
            doFlag = true;
        } catch (Exception e){
            doFlag = false;
        }
        return doFlag;

    }

    private ProductInfo insertProduct(ProductDataVO productDataVO)
    {
        boolean doFlag = false;
        try
        {
            ProductInfo productInfo= new ProductInfo();
            productInfo.setCodeValue(productDataVO.getBarCode());
            productInfo.setExtension(productDataVO.getExtension());
            productInfo.setCreateDate(DateUtil.getCurrentDate());
            productInfo.setUpdateDate(DateUtil.getCurrentDate());
            productInfo.setEnableFlag("Y");
            productInfo.setDepth(productDataVO.getDepth());
            productInfo.setBrandId(productDataVO.getBrandId());
            productInfo.setClassCode(productDataVO.getClassCode());
            productInfo.setDescription(productDataVO.getDescription());
            productInfo.setGrossWeight(productDataVO.getGrossWeight());
            productInfo.setGtin(productDataVO.getGtin());
            productInfo.setHeight(productDataVO.getHeight());
            productInfo.setItemName(productDataVO.getItemName());
            productInfo.setNetContent(productDataVO.getNetContent());
            productInfo.setPackagingMaterialCode(productDataVO.getPackagingMaterialCode());
            productInfo.setShortDescription(productDataVO.getShortDescription());
            productInfo.setPackagingTypeCode(productDataVO.getPackagingTypeCode());
            productInfo.setWidth(productDataVO.getWidth());
            productInfo.setNetWeight(productDataVO.getNetWeight());
            productInfo.setProductMaxIndex(1);
            productInfo.setCodeValueStatus(productDataVO.getCodeValueStatus());
            //logger.info("待入库的正式的产品库 productInfo="+productInfo.toString());
            this.productInfoDao.save(productInfo);
            doFlag = true;
            return productInfo;
        } catch (Exception e)
        {
            doFlag = false;
            return null;
        }
    }
    //ProductDataVO getProductDataFromHttpGet(String url);



    /**
     * 生成二维码数据
     * 必须是productMaxIndex  >1
     */
    public void encoderQRCode()
    {
        PageVO pageVO = new PageVO();
        List<ProductInfo> list = null;
        pageVO.setPageSize(200);
        logger.info("start 定时生成二维码数据");
        list = this.productService.getProductInfoListForQRCodePNG(pageVO);

        if (list!=null&&list.size()>0)
        {
            this.codeService.encoderQRCode(list);
        }
    }

    /**
     * 生成二维码图片
     */

    public void ProductQRCodeToPng()
    {
        PageVO pageVO = new PageVO();
        List<QrCode> list = null;
        logger.info("开始生成二维码图片");
        list = this.codeService.getQrCodeList(pageVO);
        String path = this.staticParameterService.getParameterValueByName("productQRPath");
        if (list!=null&&list.size()>0)
        {
            for (QrCode qrCode:list)
            {
                try{
                    this.codeService.QrCodeToPng(qrCode.getCodeValue(),path);
                    //logger.info("生成二维码图片成功");
                }
                catch (Exception e){
                    logger.error("生成二维码图片异常："+qrCode.toString());
                }
            }
        }
    }

}
